//
//
//  Created by lina on 11-11-15.
//  Copyright (c) 2011年 Sina. All rights reserved.
//

#import "CustomTabBarController.h"
#import "wxAppDelegate.h"
#import "UIBadgeView.h"

@implementation CustomTabBarController

#ifdef CustomTabBar
@synthesize currentSelectedIndex;
@synthesize buttons,cusTomTabBarView,customTabBarDelegate;
static BOOL FIRSTTIME =YES;
#endif

// Create a view controller and setup it's tab bar item with a title and image
-(UIViewController*) viewControllerWithTabTitle:(NSString*) title image:(UIImage*)image
{
  UIViewController* viewController = [[[UIViewController alloc] init] autorelease];
  viewController.tabBarItem = [[[UITabBarItem alloc] initWithTitle:title image:image tag:0] autorelease];
  return viewController;
}

// Create a custom UIButton and add it to the center of our tab bar
-(void) addCenterButtonWithImage:(UIImage*)buttonImage highlightImage:(UIImage*)highlightImage
{
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
    [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [button setBackgroundImage:highlightImage forState:UIControlStateHighlighted];

    wxAppDelegate * appDelegate = (wxAppDelegate*)[[UIApplication sharedApplication] delegate]; 
    [button addTarget:appDelegate action:@selector(tabBarCenterButtonClicked) forControlEvents:UIControlEventTouchUpInside];

    // set frame
    CGFloat heightDifference = buttonImage.size.height - self.tabBar.frame.size.height;
    if (heightDifference < 0)
    button.center = self.tabBar.center;
    else
    {
    CGPoint center = self.tabBar.center;
    center.y = center.y - heightDifference/2.0;
    button.center = center;
    }
    
    float y = button.center.y-self.tabBar.frame.origin.y;	
    CGPoint center = button.center;
    center.y=y;	
    button.center=center;

#ifdef CustomTabBar
    [cusTomTabBarView addSubview:button];
#else
    [self.tabBar addSubview:button];
#endif
}

#ifdef CustomTabBar

// custom
- (void)viewDidAppear:(BOOL)animated{
	if (FIRSTTIME) {
		[[NSNotificationCenter defaultCenter] removeObserver:self name:@"hideCustomTabBar" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(hideCustomTabBarWithoutAnimation)
													 name: @"hideCustomTabBar"
												   object: nil];
		[[NSNotificationCenter defaultCenter] removeObserver:self name:@"bringCustomTabBarToFront" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(bringCustomTabBarToFrontWithoutAnimation)
													 name: @"bringCustomTabBarToFront"
												   object: nil];
		[[NSNotificationCenter defaultCenter] removeObserver:self name:@"setBadge" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(setBadge:)
													 name: @"setBadge"
												   object: nil];
		
		slideBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"slides.png"]];
		[self hideRealTabBar];
		[self customTabBar];
		FIRSTTIME = NO;
	}
}

- (void)hideRealTabBar{
	for(UIView *view in self.view.subviews){
		if([view isKindOfClass:[UITabBar class]]){
			view.hidden = YES;
			break;
		}
	}
}

//设置badge
- (void)setBadge:(NSNotification *)_notification{
	NSString *badgeValue = [_notification object];
	UIButton *btn = [self.buttons objectAtIndex:self.selectedIndex];
	UIBadgeView *badgeView = [[UIBadgeView alloc] initWithFrame:CGRectMake(btn.bounds.size.width/2, 0, 30, 20)];
	badgeView.badgeString = badgeValue;
	badgeView.badgeColor = [UIColor blueColor];
	badgeView.tag = self.selectedIndex;
	badgeView.delegate = self;
	[btn addSubview:badgeView];
	[badgeView release];
}

//自定义tabbar
- (void)customTabBar
{
	//获取tabbar的frame
	CGRect tabBarFrame = self.tabBar.frame;
	backGroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 49)];
	cusTomTabBarView = [[UIView alloc] initWithFrame:tabBarFrame];
	//设置tabbar背景
	[cusTomTabBarView addSubview:backGroundImageView];
	[backGroundImageView release];
	cusTomTabBarView.backgroundColor = [customTabBarDelegate backgroundColorForTabBar:self];
	
	//创建按钮
	int viewCount = self.viewControllers.count > 5 ? 5 : self.viewControllers.count;
	self.buttons = [NSMutableArray arrayWithCapacity:viewCount];
	double _width = 320 / viewCount;
	double _height = self.tabBar.frame.size.height;
	for (int i = 0; i < viewCount; i++) {
		UIViewController *v = [self.viewControllers objectAtIndex:i];
		UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
		btn.frame = CGRectMake(i*_width, 0, _width, _height);
		[btn addTarget:self action:@selector(selectedTab:) forControlEvents:UIControlEventTouchDown];
		btn.tag = i;
		[btn setImage:v.tabBarItem.image forState:UIControlStateNormal];
		[btn setImageEdgeInsets:UIEdgeInsetsMake(-2, 0, 0, 0)];
		//添加标题
		UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _height-18-2, _width, _height-30)];
		titleLabel.backgroundColor = [UIColor clearColor];
		titleLabel.text = v.tabBarItem.title;
		[titleLabel setFont:[UIFont systemFontOfSize:12]];
		titleLabel.textAlignment = 1;
		titleLabel.textColor = [customTabBarDelegate normalTitleColor:self];
        titleLabel.tag = i+100;
		[btn addSubview:titleLabel];
		[titleLabel release];
		
		[self.buttons addObject:btn];
		//添加按钮之间的分割线,第一个位置和最后一个位置不需要添加
//		if (i>0 && i<4) {
//			UIImageView *splitView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"split"]];
//			splitView.frame = CGRectMake(i*_width-1,0,splitView.frame.size.width,splitView.frame.size.height);
//			[cusTomTabBarView addSubview:splitView];
//			[splitView release];
//		}
		
		//添加Badge
//		if (v.tabBarItem.badgeValue) {
//			UIBadgeView *badgeView = [[UIBadgeView alloc] initWithFrame:CGRectMake(_width/2, 0, 30, 20)];
//			badgeView.badgeString = v.tabBarItem.badgeValue;
//			badgeView.badgeColor = [UIColor orangeColor];
//			[btn addSubview:badgeView];
//			[badgeView release];
//		}
		[cusTomTabBarView addSubview:btn];
	}

    [customTabBarDelegate selectedItemImagesForTabBar:self buttons:self.buttons];
	[self.view addSubview:cusTomTabBarView];
//	[cusTomTabBarView addSubview:slideBg];
	[cusTomTabBarView release];
    if ([wxAppDelegate getAppDelegate].isLogin) {
        self.currentSelectedIndex = 0;
    }
    else{
        self.currentSelectedIndex = 0;
    }
    [self selectedTab:[buttons objectAtIndex:self.currentSelectedIndex]];
	[self performSelector:@selector(slideTabBg:) withObject:[self.buttons objectAtIndex:1]];
}

#pragma mark - button
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [customTabBarDelegate customTabBarDidSelectItem];
    }
}

//切换tabbar
- (void)selectedTab:(UIButton *)button
{
    if ([wxAppDelegate getAppDelegate].isLogin == NO && button.tag != 0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要登录才能看到其他内容哟。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        [alert release];
        return;
    }
    for(int i = 0; i < [self.buttons count]; i++)
    {
        UIButton *thisButton = (UIButton*)[self.buttons objectAtIndex:i];
        UILabel * label = (UILabel*)[thisButton viewWithTag:(thisButton.tag+100)];
        if(thisButton == button)
        {
            thisButton.selected = YES;
            label.textColor = [customTabBarDelegate selectedTitleColor:self];
        }
        else
        {
            thisButton.selected = NO;
            label.textColor = [customTabBarDelegate normalTitleColor:self];
        }
    }

	if (self.currentSelectedIndex == button.tag) {
		[[self.viewControllers objectAtIndex:button.tag] popToRootViewControllerAnimated:NO];
		return;
	}
	self.currentSelectedIndex = button.tag;
	self.selectedIndex = self.currentSelectedIndex;
	[self performSelector:@selector(slideTabBg:) withObject:button];
}

//将自定义的tabbar显示出来
- (void)bringCustomTabBarToFrontWithoutAnimation
{
    [self performSelector:@selector(hideRealTabBar)];
    [cusTomTabBarView setHidden:NO];
}

- (void)bringCustomTabBarToFront{
    [self performSelector:@selector(hideRealTabBar)];
    [cusTomTabBarView setHidden:NO];
//    CAKeyframeAnimation * animation; 
//	animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; 
//	animation.duration = 0.25;
//	animation.delegate = self;
//	animation.removedOnCompletion = YES;
//	animation.fillMode = kCAFillModeForwards;
//	NSMutableArray *values = [NSMutableArray array];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.0, 0.0, 0.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
//	animation.values = values;
//	[cusTomTabBarView.layer addAnimation:animation forKey:nil];
}

- (void)hideCustomTabBarWithoutAnimation
{
    [self performSelector:@selector(hideRealTabBar)];
    [cusTomTabBarView setHidden:YES];
}

//隐藏自定义tabbar
- (void)hideCustomTabBar
{
	[self performSelector:@selector(hideRealTabBar)];
//    CAKeyframeAnimation * animation; 
//	animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; 
//	animation.duration = 0.1;
//	animation.delegate = self;
//	animation.removedOnCompletion = YES;
//	animation.fillMode = kCAFillModeForwards;
//	NSMutableArray *values = [NSMutableArray array];
//	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.0, 0.0, 0.0)]];
//	animation.values = values;
//	[cusTomTabBarView.layer addAnimation:animation forKey:nil];
}

//动画结束回调
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if (anim.duration==0.1) 
    {
        [cusTomTabBarView setHidden:YES];
    }
}

//切换滑块位置
- (void)slideTabBg:(UIButton *)btn{
//	[UIView beginAnimations:nil context:nil];  
//	[UIView setAnimationDuration:0.20];  
//	[UIView setAnimationDelegate:self];
//	slideBg.frame = btn.frame;
//	[UIView commitAnimations];
//	CAKeyframeAnimation * animation; 
//	animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; 
//	animation.duration = 0.50; 
//	animation.delegate = self;
//	animation.removedOnCompletion = YES;
//	animation.fillMode = kCAFillModeForwards;
//	NSMutableArray *values = [NSMutableArray array];
//	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
//	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]]; 
//	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]]; 
//	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
//	animation.values = values;
//	[btn.layer addAnimation:animation forKey:nil];
}


- (void) dealloc{
	
	[cusTomTabBarView release];
	[slideBg release];
	[buttons release];
	[backGroundImageView release];
	[super dealloc];
}

#endif

@end
